package com.shitou.shitouproduct.service.impl;

import com.shitou.shitoucommons.utils.RespBean;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;

import com.shitou.shitouproduct.dao.CarouselDao;
import com.shitou.shitouproduct.entity.CarouselEntity;
import com.shitou.shitouproduct.service.CarouselService;

@Transactional
@Service("carouselService")
public class CarouselServiceImpl extends ServiceImpl<CarouselDao, CarouselEntity> implements CarouselService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CarouselEntity> page = this.page(
                new Query<CarouselEntity>().getPage(params),
                new QueryWrapper<CarouselEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public RespBean getShow() {
        List<CarouselEntity> status = this.list(new QueryWrapper<CarouselEntity>().eq("status", 1));
        // TODO 如果获得为空，那么从数据库中寻找一串数据进行展示


        return RespBean.success().put("data", status);
    }


    @Override
    public boolean saveOrUpdateBatch(Collection<CarouselEntity> entityList) {
        Collection<CarouselEntity> update = new ArrayList<>();
        Collection<CarouselEntity> insert = new ArrayList<>();
        List<CarouselEntity> list = this.list();
        Map<Long, Long> map = new LinkedHashMap<>();
        for (CarouselEntity carousel : list) {
            map.put(carousel.getSpuId(), carousel.getId());
        }

        Iterator<CarouselEntity> iterator = entityList.iterator();

        while (iterator.hasNext()) {
            CarouselEntity carousel = iterator.next();
            Long aLong = map.get(carousel.getSpuId());
            if ( aLong != null ){
                carousel.setId(aLong);
                update.add(carousel);
            }else {
                insert.add(carousel);
            }
        }

        boolean b = this.updateBatchById(update);
        boolean b1 = this.saveBatch(insert);

        return b && b1;
    }
}
